import _ from 'lodash';
import { message, Select } from 'antd';
import { NAME_SPACE, SearchParams, AddForm, Default_Columns } from '../components/CarInfoManage/config';
import { getPageList, getList, insertCar, stopUserCarByCarId, getUserList, insertUserCar } from '../services/carInfoManage';
import moment from 'moment';

// 更新编辑
function handleEditItem(columns, editItem) {
  let newItem = {};
  columns.map((item) => {
      newItem[item] = editItem[item];
  });
  return newItem;
} 

export default {
  namespace: NAME_SPACE,
  state:{
    loading: false,
    pageNo: 1,
    pageSize: 20,
    total: 0,
    searchParams: {...SearchParams},
    oldSearchParams: {...SearchParams},
    selectedRowKeys: [],
    dataList: [],
    carList: [],
    // 详情可见
    detailsModelVisable: false,
    details: {},
    // 添加可见
    addModelVisable: false,
    addForm: {...AddForm},
    default_columns: {...Default_Columns},
    // 编辑
    edit: false,
    // 人员姓名
    car: '',
    // id
    modifyId: '',
    userList: [],
    // 绑定可见
    BindingVisable: false,
    bindCarId:'',
    bindUserId: '',
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({pathname, query}) => {
        if(pathname == '/carInfoManage'){
          dispatch({
            type:'init',
            payload:{}
          });
        }
      });
    },
  },
  effects: {
    *init({payload},{select, put, call}){
      yield put({
        type: 'getList',
        payload: {type: 'search'}
      });

      yield put({
        type: 'getCarList',
        payload: {}
      })

      yield put({
        type: 'getUserList',
        payload: {}
      })
    },
    *getList({payload},{select, put, call}){
      let {type: searchType, delNum} = payload;
      let {searchParams, oldSearchParams, total, pageSize, pageNo} = yield select(state => state[NAME_SPACE]);
      let newPageNo = 1, newPageSize = 20;
      switch (searchType) {
        case "search":
            oldSearchParams = Object.assign({}, searchParams);
            break;
        case "page":
            newPageNo = pageNo;
            newPageSize = pageSize;
        break;
            case "del":
            if (total===1 || (total-(pageNo)*pageSize - delNum)>0) {
                newPageNo = pageNo;
            }else{
                newPageNo = pageNo-1;
            }
            break;
        default :
            break;
      }
      yield put({
        type: 'updateState',
        payload: {
          loading: true
        }
      })
      const result = yield call(getPageList, {
        ...oldSearchParams,
        rows: newPageSize,
        page: newPageNo,
      })
      // console.log(result)
      if(result.rc == 0){
        yield put({
          type: 'updateState',
          payload: {
            dataList: result.ret.item,
            total: result.ret.count,
            pageNo: newPageNo,
            pageSize: newPageSize,
            loading: false,
          }
        })
      }else{
        message.error('数据加载错误')
        yield put({
          type: 'updateState',
          payload: {
            dataList: [],
            total: 0,
            pageNo: 1,
            pageSize: 0,
            loading: false,
          }
        })
      }
    },
    *getCarList({payload},{select, put, call}){
      let {searchParams} = yield select(state => state[NAME_SPACE]);
      const result = yield call(getList, {...searchParams})
      if(result.rc == 0){
        yield put ({
          type: 'updateState',
          payload:{
            carList: _.uniqBy( result.ret, 'carId'),
          }
        })
      }
    },
    *getDetail({payload},{select, put, call}){
      const {type, id} = payload
    },
    *add({payload},{select, put, call}){
      const { addForm } = yield select(state => state[NAME_SPACE]);
      const result = yield call(insertCar, {...addForm})
      if( result.rc == 0 ){
        message.success('新增成功')
        yield put({
          type: 'getList',
          payload: {type: 'search'}
        })
        yield put({
          type: 'getCarList',
          payload: {}
        })
      }else{
        message.error('新增失败')
      }
    },
    // 解除绑定
    *stopUserCarByCarId({payload},{select, put, call}){
      const {id} = payload
      // console.log(id)
      const result = yield call(stopUserCarByCarId, {carId: id})
      if(result.rc == 0){
        message.success('解除绑定成功')
        yield put({
          type: 'getList',
          payload: {type: 'page'}
        })
      }else{
        message.error('操作失败')
      }
    },
    // 获取人员列表
    *getUserList({payload},{select, put, call}){
      const result = yield call(getUserList, {loginType: '2', status: '1'})
      if(result.rc == 0){
        yield put({
          type: 'updateState',
          payload: {
            userList: result.ret
          }
        })
      }else{
        message.error('获取数据失败')
      }
    },
    // 绑定
    *insertUserCar({payload},{select, put, call}){
      const {bindCarId, bindUserId} = yield select(state => state[NAME_SPACE])
      const result = yield call(insertUserCar, {carId: bindCarId, userId: bindUserId })
      if(result.rc == 0){
        message.success('绑定成功')
        yield put({
          type: 'getList',
          payload: {type: 'page'}
        })
      }else{
        message.error('操作失败')
      }
    },
    *_modfiy({payload},{select, put, call}){},
    *_delete({payload},{select, put, call}){},
  },
  reducers:{
    updateState(state, { payload }) {
      return { ...state, ...payload };
    },
    updateSubState(state, { payload }) {
        let { data, sub } = payload;
        return {
            ...state,
            [sub]: {
                ...state[sub],
                ...data,
            }
        }
    },
  },
}